package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.Gift;
import cn.pconline.autoclub.entity.GiftConversion;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.GiftService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.r.client.RClient;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.web.EnvUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author ppc
 */
@Controller
public class GiftController {

    @Autowired
    private GiftService giftService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SystemConfig systemConfig;
    private static final int STATUS_NOCOMMODITY = -1;//没货
    private static final int STATUS_NOGOLD = -2;//没金币
    @Autowired
    private IntfService intfService;
    @Autowired
    private ClubService clubService;
    private static final Logger log = LoggerFactory.getLogger(GiftController.class);
    private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    private static final int STATUS_FORM_ERROR = -3; //表单验证错误
    private static final int STATUS_TEXT_ERROR = -4;//纯文本提示错误码
    private static final int STATUS_ALLOW_TO_COVERSION = 0;//允许进行礼品兑换
    private static final int STATUS_NOT_ALLOW_TO_COVERSION = 1;//不允许进行礼品兑换
    private static final int STATUS_MAX_PAGESIZE = 100;
    private static final int STATUS_MIN_PAGESIZE = 1;
    private static final int STATUS_NOLOGIN_ERROR = AppUtils.STATUS_NOLOGIN_ERROR;//没登录
    private static final int STATUS_PERMISSIONS_ERROR = AppUtils.STATUS_PERMISSIONS_ERROR;//没加入车友会

    /**
     * ajax操作的错误信息提示
     *
     * @param resp
     * @param msg
     * @param field
     */
    private void errorMsg(HttpServletResponse resp, String field, String msg, String callback) {
        resp.setCharacterEncoding("UTF-8");
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            PrintWriter out = resp.getWriter();
            String json = new JSONBuilder()
                    .put("statusCode", STATUS_FORM_ERROR)
                    .put("message", msg)
                    .put("field", field)
                    .toString();
            if (StringUtils.isBlank(callback)) {
                out.println(json);
            } else {
                out.println(callback + "(" + json + ")");
            }
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private void printMsg(HttpServletResponse resp, String msg, int code, String callback) {
        resp.setCharacterEncoding("UTF-8");
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            PrintWriter out = resp.getWriter();
            String json = new JSONBuilder()
                    .put("statusCode", code)
                    .put("message", msg)
                    .toString();
            if (StringUtils.isBlank(callback)) {
                out.println(json);
            } else {
                out.println(callback + "(" + json + ")");
            }

        } catch (IOException ex) {
            log.error("set printMsg fail!", ex);
        }
    }

    private void printMsg(HttpServletResponse resp, String msg, int code, double gold, String callback) {
        resp.setCharacterEncoding("UTF-8");
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            PrintWriter out = resp.getWriter();
            String json = new JSONBuilder()
                    .put("statusCode", code)
                    .put("gold", gold)
                    .put("message", msg)
                    .toString();
            if (StringUtils.isBlank(callback)) {
                out.println(json);
            } else {
                out.println(callback + "(" + json + ")");
            }
        } catch (IOException ex) {
            log.error("set pringMsg fail!", ex);
        }
    }

    /**
     * 返回相关Json信息
     *
     * @param resp
     * @param str
     * @param callback
     */
    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("throw exception where set response message!", ex);
        }
    }

    /**
     * 判断能否兑换礼物
     *
     * @param req
     * @param resp
     * @param gift
     * @param user
     * @param commonSessionId
     * @return
     */
    private boolean canExchangeGift(HttpServletRequest req, HttpServletResponse resp,
            Gift gift, User user, String commonSessionId, int num) {
        String callback = WebUtils.param(req, "callback", "");
        if (user == null || user.getUid() == 0) {
            printMsg(resp, "请先登录", STATUS_NOLOGIN_ERROR, callback);
            return false;
        }
        if (gift == null) {
            printMsg(resp, "找不到该礼品", STATUS_TEXT_ERROR, callback);
            return false;
        }
        //判断该礼品库存是否足够
        int curNum = gift.getCurNum();
        if (curNum < 1) {
            printMsg(resp,  "很抱歉，礼品已经被兑换完毕了，请等待我们补货！", STATUS_NOCOMMODITY, callback);
            return false;
        }
        if (curNum < num) {
            printMsg(resp, "很抱歉，剩"+curNum+"个礼品可以兑换了，请等待我们补货", STATUS_NOCOMMODITY, callback);
            return false;
        }
        // 判断金币是否足够
        long gold = giftService.getCoinsByUserId(commonSessionId, user.getUid());
        if (gold < gift.getGold()*num) {
            printMsg(resp, "兑换失败,", STATUS_NOGOLD, gift.getGold()*num - gold, callback);
            return false;
        }
        return true;
    }

    @ResponseBody
    @RequestMapping(value = "/gift/canExchangeGift", method = RequestMethod.GET)
    public void canExchangeGift(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        int num = WebUtils.paramInt(req, "num", 1);
        String callback = WebUtils.param(req, "callback", "");
        if(num == 0){
            printMsg(resp, "请填写正确的兑换数量", STATUS_TEXT_ERROR, callback);
            return;
        }
        Gift gift = giftService.find(giftId);
        User user = userAuth.getUser(req, resp);
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(req, systemConfig.getUserSessionName());
        if (!canExchangeGift(req, resp, gift, user, commonSessionId, num)) {
            return;
        }
        printMsg(resp, "可以兑换", STATUS_ALLOW_TO_COVERSION, gift.getGold(), callback);
    }

    /**
     * 兑换礼品接口
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/gift/createConversion", method = RequestMethod.POST)
    public void createConversion(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        String truename = WebUtils.param(req, "truename", "");
        String province = WebUtils.param(req, "province", "");
        String city = WebUtils.getAreaPlaceByReq(req, "city", "");
        String address = WebUtils.param(req, "address", "");
        String postcode = WebUtils.param(req, "postcode", "");
        String phone = WebUtils.param(req, "phone", "");
        int num = WebUtils.paramInt(req, "num", 0);
        String callback = WebUtils.param(req, "callback", "");
        int ADDRESS_LENGTH = 100;
        if (num == 0) {
            errorMsg(resp, "num", "请填写正确的兑换数量", callback);
            return;
        }
        if (StringUtils.isBlank(truename)) {
            errorMsg(resp, "name", "请填写真实姓名", callback);
            return;
        } else if (truename.length() > ClubController.INPUT_MAX_LENGTH) {
            errorMsg(resp, "name", "非法真实姓名", callback);
            return;
        }

        if (StringUtils.isBlank(province) || province.equals("请选择省份")) {
            errorMsg(resp, "province", "请选择省份", callback);
            return;
        } else if (province.length() > ClubController.INPUT_MAX_LENGTH) {
            errorMsg(resp, "province", "非法省份名称", callback);
            return;
        }
        if (StringUtils.isBlank(city) || city.equals("请选择地区")) {
            errorMsg(resp, "city", "请选择城市", callback);
            return;
        } else if (city.length() > ClubController.INPUT_MAX_LENGTH) {
            errorMsg(resp, "city", "非法城市名称", callback);
            return;
        }
        if (StringUtils.isBlank(address)) {
            errorMsg(resp, "address", "请填写详细地址", callback);
            return;
        } else if (address.length() > ADDRESS_LENGTH) {
            errorMsg(resp, "address", "详细地址不能超过" + ADDRESS_LENGTH + "字符", callback);
            return;
        }
        if (StringUtils.isBlank(postcode) || !postcode.matches(Regex.postcode.value)) {
            errorMsg(resp, "postcode", "请填写正确的邮政编码", callback);
            return;
        }
        if (StringUtils.isBlank(phone) || !phone.matches(Regex.cellphone.value)) {
            errorMsg(resp, "phone", "请填写正确的手机号码", callback);
            return;
        }
        String trueAddress = province + city + address;
        User user = userAuth.getUser(req, resp);
        Gift gift = giftService.find(giftId);
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(req, systemConfig.getUserSessionName());
        if (!canExchangeGift(req, resp, gift, user, commonSessionId, num)) {//判断金币是否足够
            return;
        }
        GiftConversion conversion = giftService.createConversion(user.getUid(), gift, truename, trueAddress, postcode, phone,num);
        if (conversion != null) {
            // 与任务接口做扣金币操作,根据结果决定是否修改订单状态
            long isSuccess = 0;
            boolean isFree = false;//是否为免费礼品
            if (gift.getGold() == 0) {//如果是免费礼品，不需要调用任务系统接口扣金币
                isFree = true;
            } else {//扣金币操作
                isSuccess = giftService.updateUserGold(commonSessionId, user.getUid(), gift.getGold()*num, num, gift.getName()); //扣金币结果
            }
            if (isSuccess > Gift.STATUS_GOLD_OK || isFree) {
                int count = giftService.updateConversionToNormal(conversion, isSuccess, num);
                if (count > 0) {
                    printMsg(resp, "兑换成功", STATUS_ALLOW_TO_COVERSION, conversion.getGold(), callback);
                } else {
                    printMsg(resp, "兑换失败", STATUS_TEXT_ERROR, callback);
                }
            } else if (isSuccess == Gift.STATUS_GOLD_ERROR) {
                printMsg(resp, "兑换失败", STATUS_TEXT_ERROR, callback);
            } else if (isSuccess == Gift.STATUS_GOLD_FAIL) {
                printMsg(resp, "金币不足", STATUS_TEXT_ERROR, callback);
            } else {
                printMsg(resp, "兑换失败", STATUS_NOGOLD, callback);
            }
        } else {
            printMsg(resp, "兑换失败", STATUS_TEXT_ERROR, callback);
        }
    }

    /**
     * 礼品列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/listGift")
    public String listGift(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 15, 0, 100);
        Pager<Gift> pager = giftService.listGift(Gift.STATUS_UP, pageNo, pageSize);
        User user = userAuth.getUser(req, resp);
        req.setAttribute("user", user);
        if (user.getUid() > 0) {
            ClubMember m = memberService.findClubMemberByUserId(user.getUid());
            if (m != null) {
                Club club = clubService.getClub(m.getClubId());
                req.setAttribute("club", club);
            }
        }
        req.setAttribute("pager", pager);
        return "template/gift/list";
    }

    /**
     * 申请兑换礼品页面
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/applyGift", method = RequestMethod.GET)
    public String gifInfo(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        Gift gift = giftService.find(giftId);
        User user = userAuth.getUser(req, resp);
        if (gift == null) {
            try {
                resp.sendError(404);
            } catch (IOException ex) {
                log.error("getInfo fail!", ex);
            }
            return "";
        }
        req.setAttribute("user", user);
        req.setAttribute("gift", gift);
        return "template/gift/info";
    }

    /**
     * 登录页面跳转(不是以.do不会有systemconfig的配置)
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/goToLogin", method = RequestMethod.GET)
    public String goToLogin(HttpServletRequest req, HttpServletResponse resp) {
        return "template/gift/unlogin";
    }

    /**
     * 用户兑换礼品信息(app接口）
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/gift/listConversionByUserId4App.do", method = RequestMethod.GET)
    public void listConversionByUserId4App(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONObject jsonObject = new JSONObject();

        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            AppUtils.setNoLoginCode(json);
            printMsg(response, json.toString(), callback);
            return;
        }

        Pager<GiftConversion> pager = giftService.listConversion(userLogin.getUid(), 0L, 1, 1);
        if (pager != null) {
            jsonObject.put("userId", userLogin.getUid());//用户ID
            jsonObject.put("userName", userLogin.getNickname());//用户昵称
            jsonObject.put("exchangeCount", pager.getTotal());//兑换记录总数

            String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
            long gold = giftService.getCoinsByUserId(commonSessionId, userLogin.getUid());
            jsonObject.put("goldCount", gold);//金币总数(从任务系统获取）

            jsonObject.put("userImg", WebUtils.face(userLogin.getUid(), DEFAULT_AUTHORPHOTO_SIZE));
        }
        json.put("data", jsonObject);
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取用户礼品兑换列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 根据UserID获取金币数，从任务系统获取
     *
     * @param uid
     * @return
     */
    public long getCoinsByUserId(long uid) {
        RClient rClient = EnvUtils.getEnv().getBean(RClient.class);
        String tastRoot = EnvUtils.getEnv().getBean(SystemConfig.class).getTaskRoot();

        long coins = 0L;
        String jsonString = "";
        try {
            jsonString = rClient.get(tastRoot + "/intf/clubgc/getUserInfo.do?userId=" + uid, null, 1, TimeUnit.SECONDS);
            JSONObject json = JSONObject.parseObject(jsonString);
            coins = Long.parseLong(json.getString("goldCount"));
        } catch (Exception e) {
            log.error("Retrieve coins error:uid: {}, result: {}", uid, jsonString);
            log.error("Retrieve coins error", e);
        }
        return coins;
    }

    /**
     * 礼品兑换列表显示(APP接口）
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/gift/listGift4App", method = RequestMethod.GET)
    public void listGift4App(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        Pager<Gift> pager = giftService.listGift(Gift.STATUS_UP, pageNo, pageSize);
        WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
        if (pager != null) {
            for (Gift gift : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", gift.getGiftId()); //礼品ID
                jsonObject.put("img", gift.getGiftUrl());//礼品URL
                jsonObject.put("name", gift.getName());//礼品描述
                jsonObject.put("cost", gift.getGold());//兑换礼品需要花费的金币
                jsonObject.put("link", gift.getLink());//礼品帖子URL
                //如果下回了的礼品，不返回给APP接口
                if (gift.getStatus() == Gift.STATUS_UP && gift.getCurNum() > 0) {
                    jsonObject.put("status", STATUS_ALLOW_TO_COVERSION); //可以进行兑换
                } else {
                    jsonObject.put("status", STATUS_NOT_ALLOW_TO_COVERSION);//不可以进行兑换
                }
                jsonArray.add(jsonObject);
            }
        }

        json.put("data", jsonArray);
        json.put("total", pager.getTotal());
        json.put("pageNo", pager.getPageNo());
        json.put("pageSize", pager.getPageSize());
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取礼品兑换列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 创建礼品兑换的申请信息
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/gift/createReply4ConversionInfo", method = RequestMethod.POST)
    public void createReply4ConversionInfo(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long giftId = WebUtils.paramLong(request, "giftId", 0); //礼品ID
        String realName = WebUtils.param(request, "realName", "");//真实姓名
        String provinceName = WebUtils.param(request, "provinceName", "");//省份名字
        String cityName = WebUtils.param(request, "cityName", "");//城市名字
        String address = WebUtils.param(request, "address", "");//详细地址
        String postCode = WebUtils.param(request, "postCode", "");//邮编号码
        String phoneNum = WebUtils.param(request, "phoneNum", "");//电话号码
        int num = WebUtils.paramInt(request, "num", 1);//电话号码
        JSONObject json = new JSONObject();

        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            AppUtils.setNoLoginCode(json);
            printMsg(response, json.toString(), callback);
            return;
        }

        // 判断礼品是否存在
        Gift gift = giftService.find(giftId);
        if (gift == null) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "非法参数giftId!");
            printMsg(response, json.toString(), callback);
            return;
        } else if (gift.getStatus() != Gift.STATUS_UP) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "礼品已经下架!");
            printMsg(response, json.toString(), callback);
            return;
        }

        // 必填字段检查
        if (StringUtils.isBlank(realName) || StringUtils.isBlank(address)
                || StringUtils.isBlank(postCode) || StringUtils.isBlank(phoneNum) || StringUtils.isBlank(provinceName)) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "参数不能为空realName|address|postCode|phoneNum|provinceName ！");
            printMsg(response, json.toString(), callback);
            return;
        }

        if (StringUtils.length(realName) > 50) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "姓名填写有误！");
            printMsg(response, json.toString(), callback);
            return;
        }

        if (!postCode.matches(Regex.postcode.value)) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "邮政编码填写有误！");
            printMsg(response, json.toString(), callback);
            return;
        }

        if (!phoneNum.matches(Regex.cellphone.value)) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "电话号码填写有误！");
            printMsg(response, json.toString(), callback);
            return;
        }
        
        if (StringUtils.length(address) > 80) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "详细地址不可以超过80个汉字！");
            printMsg(response, json.toString(), callback);
            return;
        }
        
        //判断该礼品库存是否足够
        int curNum = gift.getCurNum();
        if (curNum < 1) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "很抱歉，礼品已经被兑换完毕了，请等待我们补货！");
            printMsg(response, json.toString(), callback);
            return;
        }
        
        if (curNum < num) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "很抱歉，只剩"+ curNum +"个礼品可以兑换了，请等待我们补货！");
            printMsg(response, json.toString(), callback);
            return;
        }

        // 判断金币是否足够
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
        long gold = giftService.getCoinsByUserId(commonSessionId, userLogin.getUid());
        if (gold < gift.getGold()*num) {
            json.put("code", AppUtils.STATUS_PERMISSIONS_ERROR);
            json.put("message", "金币不足 ！");
            printMsg(response, json.toString(), callback);
            return;
        }

        //完整地址=省+市+详细地址
        address = provinceName + cityName + address;
        //创建礼品兑换申请记录
        GiftConversion giftConversion = giftService.createConversion(userLogin.getUid(), gift, realName, address, postCode, phoneNum, num);
        if (giftConversion == null) {
            json.put("code", AppUtils.STATUS_FAIL);
            json.put("message", "创建礼品兑换申请记录失败！");
            printMsg(response, json.toString(), callback);
            return;

        } else {
            long isSuccess = 0;
            boolean isFree = false;//是否为免费礼品
            if (gift.getGold() == 0) {//如果是免费礼品，不需要调用任务系统接口扣金币
                isFree = true;
            } else {//扣金币操作
                isSuccess = giftService.updateUserGold(commonSessionId, userLogin.getUid(), gift.getGold()*num, num, gift.getName()); //扣金币结果
            }
            if (isSuccess > Gift.STATUS_GOLD_OK || isFree) {
                int count = giftService.updateConversionToNormal(giftConversion, isSuccess, num);
                if (count > 0) {
                    json.put("code", AppUtils.STATUS_OK);
                    json.put("message", "创建礼品兑换申请记录成功！");
                    printMsg(response, json.toString(), callback);

                } else {
                    json.put("code", AppUtils.STATUS_FAIL);
                    json.put("message", "创建礼品兑换申请记录失败！");
                    printMsg(response, json.toString(), callback);
                }
            } else {
                json.put("code", AppUtils.STATUS_FAIL);
                json.put("message", "扣除金币失败！");
                printMsg(response, json.toString(), callback);
            }
        }
    }

    /**
     * 根据用户ID获取用户兑换礼品详细记录
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/gift/listConversionHistoryByUserId4App.do", method = RequestMethod.GET)
    public void listConversionHistoryByUserId4App(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            AppUtils.setNoLoginCode(json);
            printMsg(response, json.toString(), callback);
            return;
        }
        Pager<GiftConversion> pager = giftService.listConversion(userLogin.getUid(), 0L, pageNo, pageSize);
        if (pager != null) {
            for (GiftConversion giftConversion : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", giftConversion.getConversionId());//兑换礼品记录ID
                Gift gift = giftService.find(giftConversion.getGiftId());
                if (gift != null) {
                    jsonObject.put("img", gift.getGiftUrl());//礼品URL
                    jsonObject.put("name", gift.getName());//礼品名称
                }
                jsonObject.put("cost", giftConversion.getGold());//礼品兑换金币
                jsonObject.put("time", giftConversion.getCreateAt().getTime());//礼品兑换时间
                jsonObject.put("status", giftConversion.getStatus());//礼品状态

                jsonArray.add(jsonObject);
            }
        }
        json.put("data", jsonArray);
        json.put("total", pager.getTotal());
        json.put("pageNo", pager.getPageNo());
        json.put("pageSize", pager.getPageSize());
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取用户礼品兑换历史列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 根据用户ID获取用户兑换礼品详细记录(个人中心调用)
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/gift/listConversionHistoryByUserIdForUserCenter.do", method = RequestMethod.GET)
    public void listConversionHistoryByUserIdForUserCenter(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            AppUtils.setNoLoginCode(json);
            printMsg(response, json.toString(), callback);
            return;
        }
        Pager<GiftConversion> pager = giftService.listConversion(userLogin.getUid(), 0L, pageNo, pageSize);
        if (pager != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (GiftConversion giftConversion : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", giftConversion.getConversionId());//兑换礼品记录ID
                Gift gift = giftService.find(giftConversion.getGiftId());
                if (gift != null) {
                    jsonObject.put("img", gift.getGiftUrl());//礼品URL
                    jsonObject.put("name", gift.getName());//礼品名称
                }
                jsonObject.put("cost", giftConversion.getGold());//礼品兑换金币
                jsonObject.put("time", sdf.format(giftConversion.getCreateAt()));//礼品兑换时间
                jsonObject.put("status", giftConversion.getStatus());//礼品状态

                jsonArray.add(jsonObject);
            }
        }
        json.put("data", jsonArray);
        json.put("total", pager.getTotal());
        json.put("pageNo", pager.getPageNo());
        json.put("pageCount", pager.getPageCount());
        json.put("pageSize", pager.getPageSize());
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取用户礼品兑换历史列表！");
        printMsg(response, json.toString(), callback);
    }
}
